package com.CST.aspect;

import com.github.pagehelper.*;
import com.CST.annotation.*;
import com.CST.common.api.*;
import java.util.*;
import javax.servlet.http.*;
import org.apache.commons.lang3.*;
import org.aspectj.lang.*;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.*;
import org.springframework.core.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.web.context.request.*;

/**
 * @author wzw Date 2020/7/9
 * @Description
 */
@Component
@Aspect
@Order(1)
public class PageObjectAspect {

    @Around("@annotation(pagingQuery)")
    public Object pagingQuery(ProceedingJoinPoint joinPoint, PagingQuery pagingQuery)
	  throws Throwable {
	  MethodSignature signature = (MethodSignature) joinPoint.getSignature();
	  final Class<?> returnType = signature.getMethod().getReturnType();
	  if (returnType == Object.class) {
		final String pageNumParameterName = pagingQuery.pageNumParameterName();
		final String pageSizeParameterName = pagingQuery.pageSizeParameterName();

		final ServletRequestAttributes currentRequestAttributes = (ServletRequestAttributes) RequestContextHolder
		    .currentRequestAttributes();
		final HttpServletRequest request = currentRequestAttributes.getRequest();
		String pageNum = request.getParameter(pageNumParameterName);
		String pageSize = request.getParameter(pageSizeParameterName);
		pageNum = StringUtils.isEmpty(pageNum) ? "1" : pageNum;
		pageSize = StringUtils.isEmpty(pageSize) ? "10" : pageSize;

		try {

		    PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		    Object result = joinPoint.proceed();
		    if (result != null) {
			  PageInfo<?> pageInfo = new PageInfo<>((List<?>) result);
			  final List<?> list = pageInfo.getList();
			  final int pageNum1 = pageInfo.getPageNum();
			  int pageSize1 = pageInfo.getPageSize();
			  if (pageSize1 == 0) {
				pageSize1 = 10;
			  }
			  final long total = pageInfo.getTotal();
			  //计算页面总数
			  long totalPage =
				total % pageSize1 == 0 ? total / pageSize1 : (total / pageSize1) + 1;
			  return ResultPageObject.successReturn(pageSize1, total, list, pageNum1,
									    totalPage);
		    } else {
			  return ResultPageObject.successReturn(10, 0L, null, 1, 1L);
		    }
		} finally {
		    //保证线程变量被清除
		    if (PageHelper.getLocalPage() != null) {
			  PageHelper.clearPage();
		    }
		}
	  }
	  return joinPoint.proceed();

    }

}
